from django.shortcuts import render, redirect
from django.http import JsonResponse
from apps.web.forms.manage import WikiModelForm
from django.urls import reverse
from apps.web import models
from utils import encrypt
from django.views.decorators.csrf import csrf_exempt
from tools import cos


def wiki(request, project_id):
    wiki_id = request.GET.get('wiki_id')
    if not wiki_id or not wiki_id.isdecimal():
        return render(request, 'web/wiki.html')
    wiki_obj = models.Wiki.objects.filter(id=wiki_id, project_id=project_id).first()
    return render(request, 'web/wiki.html', {'wiki_obj': wiki_obj})


def wiki_add(request, project_id):
    """wiki文档添加"""
    if request.method == 'GET':
        # 实例化对象
        form = WikiModelForm(request)
        return render(request, 'web/wiki_add.html', {'form': form})
    form = WikiModelForm(request, data=request.POST)
    if form.is_valid():
        # 判断当前文档是否有父目录
        if form.instance.parent:
            form.instance.depth = form.instance.parent.depth + 1
        else:
            form.instance.depth = 1

        form.instance.project = request.tracer.project
        form.save()
        url = reverse('manage:wiki', kwargs={'project_id': project_id})
        return redirect(url)
    return render(request, 'web/wiki_add.html', {'form': form})


def catalog(request, project_id):
    """获取目录"""
    # 从数据库查找该项目的所有数据
    # 返回列表
    # data_list = models.Wiki.objects.filter(project_id=project_id).values_list('id', 'title', 'parent')
    # 返回字典
    data_list = models.Wiki.objects.filter(project_id=project_id).values('id', 'title', 'parent_id').order_by('depth',
                                                                                                              'id')
    return JsonResponse({'status': True, 'data': list(data_list)})


def delete(request, project_id, wiki_id):
    """wiki文档删除"""
    # 通过wiki_id来查找并删除当前文档
    models.Wiki.objects.filter(id=wiki_id, project_id=project_id).delete()
    url = reverse('manage:wiki', kwargs={'project_id': project_id})
    return redirect(url)


def edit(request, project_id, wiki_id):
    """文档修改"""
    wiki_obj = models.Wiki.objects.filter(project_id=project_id, id=wiki_id).first()
    if not wiki_obj:
        url = reverse('manage:wiki', kwargs={'project_id': project_id})
        return redirect(url)
    if request.method == 'GET':
        form = WikiModelForm(request, instance=wiki_obj)
        return render(request, 'web/wiki_edit.html', {'form': form})
    # 若为post请求
    form = WikiModelForm(request, data=request.POST, instance=wiki_obj)
    if form.is_valid():
        if form.instance.parent:
            form.instance.depth = form.instance.parent.depth + 1
        else:
            form.instance.depth = 1

        form.instance.project = request.tracer.project
        form.save()

        url = reverse('manage:wiki', kwargs={'project_id': project_id})
        return redirect(url)
    return render(request, 'web/wiki_edit.html', {'form': form})


@csrf_exempt
def upload(request, project_id):
    """
    markdown插件上传图片
    :param request:
    :return:
    """
    result = {
        "success": 0,
        "message": None,
        "url": None,
    }
    # print('收到图片')
    # print(request.FILES)
    # 文件对象
    img_obj = request.FILES.get('editormd-image-file')
    if not img_obj:
        result['message'] = '文件不存在'
    # 拿到文件名后缀
    ext = img_obj.name.rsplit('.')[-1].lower()
    # 随机文件名
    key = '{}.{}'.format(encrypt.uid(request.tracer.user.mobile_phone), ext)
    bucket = request.tracer.project.bucket
    # 文件对象上传到当前项目的桶中
    img_url = cos.upload_file(bucket, request.tracer.project.region, img_obj, key)
    print(img_url)
    result['success'] = 1
    result['url'] = img_url
    return JsonResponse(result)
